<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NoteX - 您的智能笔记</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4CAF50;
            --secondary-color: #2196F3;
            --text-color: #333;
            --bg-color: #fff;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            color: var(--text-color);
            background: #ffffff;
            height: 100vh;
            margin: 0;
            overflow: hidden;
        }

        .app-container {
            display: flex;
            height: 100vh;
            background: #ffffff;
        }

        .sidebar {
            width: 250px;
            min-width: 250px;
            background: #ffffff;
            border-right: 1px solid #e5e7eb;
            padding: 20px;
            overflow-y: auto;
        }

        .main-content {
            flex: 1;
            display: flex;
            overflow: hidden;
        }

        .notes-area {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .ai-assistant {
            width: 380px;
            min-width: 320px;
            max-width: 600px;
            border-left: 1px solid #e5e7eb;
            display: flex;
            flex-direction: column;
            background: #ffffff;
            height: 100vh;
            position: fixed;
            right: 0;
            top: 0;
        }

        .ai-chat-container {
            display: flex;
            flex-direction: column;
            height: 100%;
            background: #f8fafc;
        }

        .ai-chat-header {
            padding: 16px 20px;
            background: #ffffff;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .ai-avatar {
            width: 40px;
            height: 40px;
            border-radius: 20px;
            background: linear-gradient(135deg, #4299e1, #667eea);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }

        .ai-info h3 {
            font-size: 16px;
            font-weight: 600;
            color: #1a202c;
            margin: 0;
        }

        .ai-info p {
            font-size: 13px;
            color: #718096;
            margin: 2px 0 0 0;
        }

        .ai-chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .ai-message {
            max-width: 85%;
            padding: 12px 16px;
            border-radius: 12px;
            font-size: 14px;
            line-height: 1.5;
            position: relative;
            animation: messageSlide 0.3s ease;
        }

        @keyframes messageSlide {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .ai-message.ai-response {
            background: #EBF8FF;
            margin-right: auto;
            border-bottom-left-radius: 4px;
            color: #2C5282;
        }

        .ai-message.user-query {
            background: #4299E1;
            color: white;
            margin-left: auto;
            border-bottom-right-radius: 4px;
        }

        .ai-message::before {
            content: '';
            position: absolute;
            bottom: 0;
            width: 12px;
            height: 12px;
        }

        .ai-message.ai-response::before {
            left: -6px;
            background: linear-gradient(45deg, #EBF8FF 50%, transparent 50%);
        }

        .ai-message.user-query::before {
            right: -6px;
            background: linear-gradient(-45deg, #4299E1 50%, transparent 50%);
        }

        .ai-chat-input-container {
            padding: 16px 20px;
            background: #ffffff;
            border-top: 1px solid #e5e7eb;
            box-shadow: 0 -4px 6px -1px rgba(0, 0, 0, 0.05);
        }

        .ai-input-wrapper {
            display: flex;
            gap: 8px;
            align-items: center;
            background: #f8fafc;
            border: 1px solid #e5e7eb;
            border-radius: 24px;
            padding: 8px 16px;
            transition: all 0.3s ease;
        }

        .ai-input-wrapper:focus-within {
            border-color: #4299e1;
            box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
            background: #ffffff;
        }

        #aiInput {
            flex: 1;
            border: none;
            background: transparent;
            padding: 8px 0;
            font-size: 14px;
            color: #1a202c;
        }

        #aiInput:focus {
            outline: none;
        }

        #aiInput::placeholder {
            color: #a0aec0;
        }

        #sendAiBtn {
            background: transparent;
            border: none;
            color: #4299e1;
            padding: 6px;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #sendAiBtn:hover {
            background: #ebf8ff;
            transform: scale(1.1);
        }

        #sendAiBtn:active {
            transform: scale(0.95);
        }

        .ai-message .message-time {
            font-size: 11px;
            margin-top: 4px;
            opacity: 0.7;
        }

        .ai-typing {
            display: flex;
            gap: 4px;
            padding: 8px 12px;
            background: #EBF8FF;
            border-radius: 12px;
            width: fit-content;
            margin-top: 8px;
        }

        .ai-typing span {
            width: 6px;
            height: 6px;
            background: #4299E1;
            border-radius: 50%;
            animation: typing 1s infinite;
        }

        .ai-typing span:nth-child(2) { animation-delay: 0.2s; }
        .ai-typing span:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-4px); }
        }

        .note-item {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background: #ffffff;
            transition: all 0.2s ease;
            position: relative;
        }

        /* 为不同标签设置不同的背景色 */
        .note-item.tag-blue { background-color: rgba(59, 130, 246, 0.05); border-left: 4px solid rgb(59, 130, 246); }
        .note-item.tag-green { background-color: rgba(16, 185, 129, 0.05); border-left: 4px solid rgb(16, 185, 129); }
        .note-item.tag-yellow { background-color: rgba(245, 158, 11, 0.05); border-left: 4px solid rgb(245, 158, 11); }
        .note-item.tag-red { background-color: rgba(239, 68, 68, 0.05); border-left: 4px solid rgb(239, 68, 68); }
        .note-item.tag-indigo { background-color: rgba(99, 102, 241, 0.05); border-left: 4px solid rgb(99, 102, 241); }
        .note-item.tag-purple { background-color: rgba(139, 92, 246, 0.05); border-left: 4px solid rgb(139, 92, 246); }
        .note-item.tag-pink { background-color: rgba(236, 72, 153, 0.05); border-left: 4px solid rgb(236, 72, 153); }
        .note-item.tag-orange { background-color: rgba(249, 115, 22, 0.05); border-left: 4px solid rgb(249, 115, 22); }

        .note-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transform: translateY(-1px);
        }

        .tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin-right: 5px;
            transition: all 0.2s ease;
        }

        .tag:hover {
            opacity: 0.8;
        }

        .dark-mode {
            --text-color: #e5e7eb;
            --bg-color: #1f2937;
        }

        .tag.draggable {
            cursor: move;
        }

        .note-item.drag-over {
            background-color: #f0f9ff;
            border: 2px dashed #2196F3;
        }

        .tag.dragging {
            opacity: 0.5;
        }

        .trash-bin {
            transition: all 0.2s ease;
        }

        .trash-bin.drag-over {
            background-color: #fee2e2;
            border: 2px dashed #ef4444;
        }

        .note-item.dragging {
            opacity: 0.5;
        }

        .fade-out {
            animation: fadeOut 0.3s ease-out forwards;
        }

        @keyframes fadeOut {
            from { opacity: 1; transform: scale(1); }
            to { opacity: 0; transform: scale(0.95); }
        }

        .new-note-btn {
            width: 100%;
            padding: 10px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .new-note-btn:hover {
            background-color: #43a047;
        }

        /* 添加提示消息样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }

        .toast {
            background-color: #4CAF50;
            color: white;
            padding: 16px 24px;
            border-radius: 8px;
            margin-bottom: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            animation: slideIn 0.3s ease-out;
        }

        .toast.error {
            background-color: #ef4444;
        }

        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        @keyframes slideOut {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(100%); opacity: 0; }
        }

        .note-actions {
            display: flex;
            gap: 8px;
            opacity: 0;
            transition: opacity 0.2s ease;
        }

        .note-item:hover .note-actions {
            opacity: 1;
        }

        .note-actions button {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .edit-btn {
            background-color: #ebf8ff;
            color: #4299e1;
        }

        .edit-btn:hover {
            background-color: #bfdbfe;
            transform: scale(1.05);
        }

        .delete-btn {
            background-color: #fff5f5;
            color: #f56565;
        }

        .delete-btn:hover {
            background-color: #fecaca;
            transform: scale(1.05);
        }

        /* 确保按钮在笔记卡片上正确显示 */
        .note-item .flex {
            position: relative;
        }

        .note-item .note-actions {
            position: absolute;
            right: 0;
            top: 0;
            padding: 8px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 6px;
            z-index: 10;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- 左侧边栏 -->
        <div class="sidebar">
            <h2 class="text-xl font-bold mb-6">NoteX</h2>
            <button onclick="window.location.href='/notes/new'" class="new-note-btn mb-6">
                <i class="fas fa-plus"></i>
                <span>新建笔记</span>
            </button>
            <div class="mb-6">
                <h3 class="font-medium mb-3">核心功能</h3>
                <ul class="space-y-2">
                    <li class="flex items-center space-x-2 cursor-pointer hover:bg-gray-100 p-2 rounded" onclick="window.location.href='/notes'">
                        <i class="fas fa-book"></i>
                        <span>全部笔记</span>
                    </li>
                    <li class="flex items-center space-x-2 cursor-pointer hover:bg-gray-100 p-2 rounded" onclick="window.location.href='/notes/recent'">
                        <i class="fas fa-clock"></i>
                        <span>最近编辑</span>
                    </li>
                    <li class="flex items-center space-x-2 cursor-pointer hover:bg-gray-100 p-2 rounded" onclick="window.location.href='/trash'">
                        <i class="fas fa-trash"></i>
                        <span>回收站</span>
                    </li>
                </ul>
            </div>
            <div>
                <h3 class="font-medium mb-3">分类标签</h3>
                <ul class="space-y-2">
                    {% for tag in all_tags %}
                    <li class="flex items-center space-x-2">
                        <i class="fas fa-tag text-{{ tag_colors[tag] }}-500"></i>
                        <span>{{ tag }}</span>
                        <span class="text-xs text-gray-500">({{ tag_counts[tag]|default(0) }})</span>
                    </li>
                    {% endfor %}
                </ul>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
            <!-- 笔记区域 -->
            <div class="notes-area">
                <div class="flex justify-between items-center mb-6">
                    <div class="flex space-x-2">
                        <button class="p-2 hover:bg-gray-100 rounded">
                            <i class="fas fa-list"></i>
                        </button>
                        <button class="p-2 hover:bg-gray-100 rounded">
                            <i class="fas fa-th-large"></i>
                        </button>
                    </div>
                    <div class="flex items-center space-x-4">
                        <input type="text" placeholder="搜索笔记..." 
                            class="px-4 py-2 border rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500">
                    </div>
                </div>

                <div class="space-y-4">
                    {% for note in notes %}
                    <div class="note-item tag-{{ tag_colors[note.tags[0]] if note.tags else 'blue' }}" data-note-id="{{ note.id }}">
                        <div class="flex justify-between items-start">
                            <div class="flex-1">
                                <h3 class="font-medium">{{ note.title }}</h3>
                                <p class="text-sm text-gray-500 mt-1">{{ note.content }}</p>
                                <div class="mt-2">
                                    {% for tag in note.tags %}
                                    <span class="tag bg-{{ tag_colors[tag] }}-100 text-{{ tag_colors[tag] }}-800">{{ tag }}</span>
                                    {% endfor %}
                                </div>
                            </div>
                            <div class="flex flex-col items-end ml-4">
                                <div class="text-sm text-gray-500">{{ note.created_at }}</div>
                                <div class="note-actions mt-2">
                                    <button class="edit-btn" title="编辑笔记" data-note-id="{{ note.id }}" onclick="editNote(this.dataset.noteId)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="delete-btn" title="删除笔记" data-note-id="{{ note.id }}" onclick="deleteNote(this.dataset.noteId)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>

            <!-- AI助手区域 -->
            <div class="ai-assistant">
                <div class="ai-chat-container">
                    <div class="ai-chat-header">
                        <div class="ai-avatar">
                            <i class="fas fa-robot"></i>
                        </div>
                        <div class="ai-info">
                            <h3>AI助手</h3>
                            <p>随时为您提供智能帮助</p>
                        </div>
                    </div>
                    <div class="ai-chat-messages" id="chatMessages">
                        <div class="ai-message ai-response">
                            <div>您好！我是您的AI笔记助手，有什么可以帮您的吗？我可以帮您整理笔记、生成摘要、翻译内容等。</div>
                            <div class="message-time">现在</div>
                        </div>
                    </div>
                    <div class="ai-chat-input-container">
                        <div class="ai-input-wrapper">
                            <input type="text" id="aiInput" placeholder="输入您的问题..." class="flex-1">
                            <button id="sendAiBtn" class="flex items-center justify-center">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 提示消息容器 -->
    <div class="toast-container" id="toastContainer"></div>

    <script>
        // AI助手功能实现
        document.addEventListener('DOMContentLoaded', function() {
            const chatMessages = document.getElementById('chatMessages');
            const aiInput = document.getElementById('aiInput');
            const sendAiBtn = document.getElementById('sendAiBtn');

            // 添加消息到聊天窗口
            function addMessage(message, isAI = false) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `ai-message ${isAI ? 'ai-response' : 'user-query'}`;
                
                const now = new Date();
                const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
                
                messageDiv.innerHTML = `
                    <div>${message}</div>
                    <div class="message-time">${timeStr}</div>
                `;
                
                chatMessages.appendChild(messageDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;

                if (isAI) {
                    // 添加打字动画
                    const typingDiv = document.createElement('div');
                    typingDiv.className = 'ai-typing';
                    typingDiv.innerHTML = '<span></span><span></span><span></span>';
                    chatMessages.appendChild(typingDiv);

                    // 模拟AI思考时间
                    setTimeout(() => {
                        typingDiv.remove();
                    }, 1000);
                }
            }

            // 处理发送消息
            function handleSendMessage() {
                const message = aiInput.value.trim();
                if (message) {
                    addMessage(message, false);
                    aiInput.value = '';
                    
                    // 模拟AI响应
                    setTimeout(() => {
                        const response = getAIResponse(message);
                        addMessage(response, true);
                    }, 1000);
                }
            }

            // 事件监听
            sendAiBtn.addEventListener('click', handleSendMessage);
            
            aiInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    handleSendMessage();
                }
            });

            // 自动聚焦输入框
            aiInput.focus();
        });

        // 获取AI响应的函数
        function getAIResponse(message) {
            // 基本问候语和帮助信息
            const basicResponses = {
                '你好': '您好！请问有什么可以帮您的吗？',
                '帮助': '我可以帮您：\n1. 整理笔记内容\n2. 生成笔记摘要\n3. 翻译内容\n4. 回答您的问题\n\n示例：\n- "翻译：happy"\n- "总结笔记：[笔记内容]"\n- "分析笔记：[笔记内容]"',
                '谢谢': '不客气！如果还有什么需要帮助的，随时告诉我。'
            };

            // 检查基本回复
            for (const key in basicResponses) {
                if (message.toLowerCase().includes(key)) {
                    return basicResponses[key];
                }
            }

            // 处理翻译请求
            if (message.toLowerCase().startsWith('翻译：') || message.toLowerCase().startsWith('翻译:')) {
                const word = message.substring(3).trim();
                const translations = {
                    'happy': '快乐的、幸福的、高兴的',
                    'sad': '悲伤的、难过的',
                    'good': '好的、优秀的、善良的',
                    'bad': '坏的、糟糕的',
                    'hello': '你好、您好',
                    'goodbye': '再见、拜拜',
                    // 添加更多常用词汇翻译
                };
                return translations[word.toLowerCase()] || `抱歉，我还不知道"${word}"的翻译，但我会继续学习的！`;
            }

            // 处理笔记总结请求
            if (message.toLowerCase().startsWith('总结笔记：') || message.toLowerCase().startsWith('总结笔记:')) {
                const content = message.substring(5).trim();
                if (content.length < 10) {
                    return '请提供更多的笔记内容，这样我才能帮您进行总结。';
                }
                // 这里可以添加更复杂的笔记总结逻辑
                return `笔记总结：\n1. 主要内容：${content.substring(0, 50)}...\n2. 字数：${content.length}字\n3. 建议：可以添加标签以便更好地组织笔记。`;
            }

            // 处理笔记分析请求
            if (message.toLowerCase().startsWith('分析笔记：') || message.toLowerCase().startsWith('分析笔记:')) {
                const content = message.substring(5).trim();
                if (content.length < 10) {
                    return '请提供更多的笔记内容，这样我才能帮您进行分析。';
                }
                return `笔记分析：\n1. 内容类型：学习笔记\n2. 建议添加的标签：#学习 #笔记\n3. 改进建议：可以加入更多实例和示例来丰富内容。`;
            }

            // 如果是简单的英文单词，尝试直接翻译
            if (/^[a-zA-Z]+$/.test(message.trim())) {
                const translations = {
                    'happy': '快乐的、幸福的、高兴的',
                    'sad': '悲伤的、难过的',
                    'good': '好的、优秀的、善良的',
                    'bad': '坏的、糟糕的',
                    'hello': '你好、您好',
                    'goodbye': '再见、拜拜',
                };
                const translation = translations[message.toLowerCase()];
                if (translation) {
                    return `"${message}" 的中文含义是：${translation}`;
                }
            }

            // 默认回复
            return '抱歉，我不太理解您的问题。您可以：\n1. 输入"帮助"查看我能做什么\n2. 尝试用更简单的方式描述您的需求\n3. 使用特定的命令格式，如"翻译：单词"';
        }

        // 切换侧边栏折叠状态
        document.querySelector('.sidebar').addEventListener('click', function() {
            this.classList.toggle('collapsed');
        });

        // 切换暗黑模式
        document.querySelector('.fa-moon').addEventListener('click', function() {
            document.body.classList.toggle('dark-mode');
        });

        // 拖拽功能实现
        document.addEventListener('DOMContentLoaded', function() {
            const tags = document.querySelectorAll('.tag.draggable');
            const notes = document.querySelectorAll('.note-item');
            const trashBin = document.querySelector('.trash-bin');

            // 为标签添加拖拽事件
            tags.forEach(tag => {
                tag.addEventListener('dragstart', function(e) {
                    e.dataTransfer.setData('text/plain', this.dataset.tag);
                    this.classList.add('dragging');
                });

                tag.addEventListener('dragend', function() {
                    this.classList.remove('dragging');
                });
            });

            // 为笔记添加拖拽事件
            notes.forEach(note => {
                note.addEventListener('dragstart', function(e) {
                    this.classList.add('dragging');
                    e.dataTransfer.setData('text/plain', this.dataset.noteId || '');
                });

                note.addEventListener('dragend', function() {
                    this.classList.remove('dragging');
                });
            });

            // 为回收站添加拖拽事件
            trashBin.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.classList.add('drag-over');
            });

            trashBin.addEventListener('dragleave', function() {
                this.classList.remove('drag-over');
            });

            trashBin.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('drag-over');

                const draggedNote = document.querySelector('.note-item.dragging');
                if (draggedNote) {
                    // 添加淡出动画
                    draggedNote.classList.add('fade-out');
                    
                    // 动画结束后移除笔记
                    draggedNote.addEventListener('animationend', function() {
                        this.remove();
                    });
                }
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            const leftHandle = document.getElementById('left-resize-handle');
            const rightHandle = document.getElementById('right-resize-handle');
            const mainContainer = document.querySelector('.main-container');
            const sidebar = document.querySelector('.sidebar');
            const contentArea = document.querySelector('.content-area');
            const aiAssistant = document.querySelector('.ai-assistant');

            function initResize(handle, leftElement, rightElement) {
                let isResizing = false;
                let lastDownX = 0;

                handle.addEventListener('mousedown', function(e) {
                    isResizing = true;
                    lastDownX = e.clientX;
                    handle.classList.add('active');
                });

                document.addEventListener('mousemove', function(e) {
                    if (!isResizing) return;

                    const offsetX = e.clientX - lastDownX;
                    const rightWidth = rightElement.offsetWidth;

                    const newRightWidth = rightWidth - offsetX;
                    if (newRightWidth >= 300 && newRightWidth <= 600) {
                        mainContainer.style.gridTemplateColumns = `280px 1fr ${newRightWidth}px`;
                    }

                    lastDownX = e.clientX;
                });

                document.addEventListener('mouseup', function() {
                    isResizing = false;
                    handle.classList.remove('active');
                });
            }

            initResize(rightHandle, contentArea, aiAssistant);
        });

        // 显示提示消息的函数
        function showToast(message, type = 'success') {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast ${type === 'error' ? 'error' : ''}`;
            toast.innerHTML = `
                <i class="fas ${type === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle'} mr-2"></i>
                ${message}
            `;
            container.appendChild(toast);

            // 3秒后自动消失
            setTimeout(() => {
                toast.style.animation = 'slideOut 0.3s ease-out forwards';
                toast.addEventListener('animationend', () => {
                    container.removeChild(toast);
                });
            }, 3000);
        }

        // 删除笔记的函数
        async function deleteNote(noteId) {
            if (!confirm('确定要删除这条笔记吗？')) return;

            try {
                const response = await fetch(`/notes/${noteId}/delete`, {
                    method: 'DELETE'
                });
                const data = await response.json();
                
                if (data.success) {
                    const noteElement = document.querySelector(`[data-note-id="${noteId}"]`);
                    noteElement.style.animation = 'fadeOut 0.3s ease-out forwards';
                    noteElement.addEventListener('animationend', () => {
                        noteElement.remove();
                    });
                    showToast('笔记已删除');
                } else {
                    showToast('删除失败，请重试', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('删除失败，请重试', 'error');
            }
        }

        // 编辑笔记的函数
        function editNote(noteId) {
            window.location.href = `/notes/${noteId}/edit`;
        }

        // 保存笔记的函数
        async function saveNote(title, content, tags) {
            try {
                const formData = new FormData();
                formData.append('title', title);
                formData.append('content', content);
                formData.append('tags', tags);

                const response = await fetch('/save_note', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (result.success) {
                    showToast('笔记保存成功');
                    // 添加新笔记到列表
                    const notesList = document.querySelector('.space-y-4');
                    const noteElement = createNoteElement(result.note);
                    notesList.insertBefore(noteElement, notesList.firstChild);
                } else {
                    showToast(result.message || '保存失败，请重试', 'error');
                }
            } catch (error) {
                console.error('保存笔记出错:', error);
                showToast('保存失败，请重试', 'error');
            }
        }

        // 创建笔记元素的函数
        function createNoteElement(note) {
            const div = document.createElement('div');
            div.className = `note-item tag-${tag_colors[note.tags[0]] || 'blue'}`;
            div.dataset.noteId = note.id;
            
            div.innerHTML = `
                <div class="flex justify-between items-start">
                    <div>
                        <h3 class="font-medium">${note.title}</h3>
                        <p class="text-sm text-gray-500 mt-1">${note.content}</p>
                        <div class="mt-2">
                            ${note.tags.map(tag => `
                                <span class="tag bg-${tag_colors[tag] || 'blue'}-100 text-${tag_colors[tag] || 'blue'}-800">${tag}</span>
                            `).join('')}
                        </div>
                    </div>
                    <div class="flex flex-col items-end">
                        <div class="text-sm text-gray-500">${note.created_at}</div>
                        <div class="note-actions">
                            <button class="edit-btn" title="编辑笔记" data-note-id="${note.id}" onclick="editNote(this.dataset.noteId)">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="delete-btn" title="删除笔记" data-note-id="${note.id}" onclick="deleteNote(this.dataset.noteId)">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            return div;
        }

        function addNoteToPage(note) {
            const div = document.createElement('div');
            const tagColor = note.tags && note.tags[0] ? tag_colors[note.tags[0]] || 'blue' : 'blue';
            div.className = `note-item tag-${tagColor}`;
            div.dataset.noteId = note.id;
            
            const noteData = {
                title: note.title || '',
                content: note.content || '',
                created_at: note.created_at || '',
                tags: Array.isArray(note.tags) ? note.tags : [],
                id: note.id.toString(),
            };
            
            const tagElements = noteData.tags.map((tag) => {
                const color = tag_colors[tag] || 'blue';
                return `<span class="tag bg-${color}-100 text-${color}-800">${tag}</span>`;
            }).join('');
            
            div.innerHTML = `
                <div class="flex justify-between items-start">
                    <div>
                        <h3 class="font-medium">${noteData.title}</h3>
                        <p class="text-sm text-gray-500 mt-1">${noteData.content}</p>
                        <div class="mt-2">
                            ${tagElements}
                        </div>
                    </div>
                    <div class="flex flex-col items-end">
                        <div class="text-sm text-gray-500">${noteData.created_at}</div>
                        <div class="note-actions">
                            <button class="edit-btn" title="编辑笔记" data-note-id="${noteData.id}" onclick="editNote(this.dataset.noteId)">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="delete-btn" title="删除笔记" data-note-id="${noteData.id}" onclick="deleteNote(this.dataset.noteId)">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            const notesList = document.querySelector('.space-y-4');
            notesList.insertBefore(div, notesList.firstChild);
        }
    </script>
</body>
</html>
